package com.cx.common.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public abstract class AbstractFilter implements GlobalFilter, BaseFilter {

    protected List<String> filterUris = Arrays.asList("/login", "/logout");
    private RouteLocator routeLocator;


    protected AbstractFilter(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    protected boolean openFilter(String uri) {
        return filterUris.stream().anyMatch(uri::endsWith);
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        final ServerHttpRequest request = exchange.getRequest();
        String uri = request.getPath().value();
        // 请求放行
        if (uri.contains("/v2/api-docs")
                || openFilter(uri)) {
            return chain.filter(exchange);
        }

        return shouldFilter(exchange) ? run(exchange, chain) : chain.filter(exchange);
    }


    /**
     * 是否执行filter 默认执行
     *
     * @return
     */
    boolean shouldFilter(ServerWebExchange exchange) {
        Object shouldFilter = exchange.getAttribute("shouldFilter");
        return Objects.isNull(shouldFilter) || Boolean.TRUE.toString().equals(shouldFilter.toString());
    }

    /**
     * 执行filter
     *
     * @param exchange
     * @param chain
     * @return
     */
    public abstract Mono<Void> run(ServerWebExchange exchange, GatewayFilterChain chain);
}
